package com.sxhuayuan.parking.compenent.shiro;

import java.io.Serializable;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.web.servlet.ShiroHttpServletRequest;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.util.WebUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 默认shiro从cookie中读取sessionId以此来维持会话，
 * 在前后端分离的项目中（也可在移动APP项目使用），我们选择在ajax的请求头中传递sessionId，因此需要重写shiro获取sessionId的方式。
 */
public class MySessionManager extends DefaultWebSessionManager {

	Logger log = LoggerFactory.getLogger(getClass());

	/**
	 * session标识名称
	 */
	public static final String TOKEN_KEY = "hbtoken";

	private static final String REFERENCED_SESSION_ID_SOURCE = "Stateless request";

	public MySessionManager() {
		super();
	}

	@Override
	protected Serializable getSessionId(ServletRequest request, ServletResponse response) {
		HttpServletRequest req = WebUtils.toHttp(request);
		// cookie
		String sessionId = com.sxhuayuan.parking.utils.WebUtils.getCookie(req, TOKEN_KEY);
		// log.debug("cookie token = {}", sessionId);
		if (sessionId == null) {
			// header
			sessionId = req.getHeader(TOKEN_KEY);
			// log.debug("header token = {}", sessionId);
		}
		if (!StringUtils.isEmpty(sessionId)) {
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_SOURCE, REFERENCED_SESSION_ID_SOURCE);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID, sessionId);
			request.setAttribute(ShiroHttpServletRequest.REFERENCED_SESSION_ID_IS_VALID, Boolean.TRUE);
			return sessionId;
		} else {
			// 否则按默认规则从cookie取sessionId
			return super.getSessionId(request, response);
		}
	}

}
